var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;			//本地验证
var url = require("url");
var queryString = require("querystring");





//获取登录页
router.get('/', function (req, res) {
	// console.log('req.user:',req.user);
	// console.log('req:',req);

	res.render('web_login', {
		title: '管理系统登录页',
		arr: [{ sch: '', lib: 'active', abt: '', log: '' }],
	});

});


//提交登录请求
router.get('/login', function (req, res, next) {
	// console.log('req.user:',req.user);

	console.log('req.url的值', req.url)			//req.url是字符串，req.query是等同的对象。
	var referrer = req.query.referrer;
	console.log('referrer的值', referrer)				//上一个网页的url
	var URL = req.query.URL;
	console.log('URL的值', URL)							//当前url
	var referrerObj = url.parse(req.query.referrer, true).query
	// var referrerObj = url.parse(req.url, true).query.referrer
	console.log('referrerObj的值', referrerObj)
	var URLObj = url.parse(req.query.URL, true).query		//URL本身就是web_login_test.ensureAuthenticated传过来的url
	// var URLObj = url.parse(req.url, true).query.URL
	console.log('URLObj的值', URLObj)

	// 这里(内部)调用了web_login_test文件的passport.use函数,并从中得到了user的值,并赋值给了req.user
	passport.authenticate('local', function (err, user, info) {		
		if (err) {
			return next(err);
		}
		if (!user) {									//user为空
			req.flash('error_msg', info.message);
			return res.redirect('/login');
		}
		console.log('现在在Login之前')
		req.logIn(user, function (err) {						//这里内部会调用passport.serializeUser()

			if (err) {
				return next(err);
			}
			var user_name=user.sys_name;
			console.log('user_name:',user_name);
			// console.log('req.user:',req.user);
				
			req.flash('success_msg', '登录成功...');			//第一个参数是key,第二个参数是value
			console.log('success_msg', '登录成功...');

			if (referrer != 'http://localhost:3000/login') {	//说明源网页的url不等于/loginPg,则只能来源于/search页面
				if (URLObj.sType && URLObj.content) {
					// return res.redirect('/search' + '?sType=' + URLObj.sType + '&content=' + URLObj.content+'&username='+user_name);
					return res.redirect('/search' + '?sType=' + URLObj.sType + '&content=' + URLObj.content);
				}
				if(referrer != ''){
					// return res.redirect(referrer+'?username='+user_name);
					return res.redirect(referrer);
				}
				else{
					return res.redirect(URL);
				}
			}

			// return res.redirect('/menu/net'+'?username='+user_name);
			return res.redirect('/menu/net');
		});
	})(req, res, next);									//相当于 函数返回值（req,res.next）
});


//退出登录
router.get('/loginOut', function (req, res) {
	req.logout();
	res.redirect('/login');
});

module.exports=router